/**	
 * Author : Mht
 * Desc : For 2016 RDM 
 */
package configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

import lombok.extern.log4j.Log4j;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author Mht
 * @date May 10, 2016
 */
@Log4j
@Configuration
public class RedisConfiguration {

	@Autowired
	private Environment env;

	public RedisConfiguration() {
		log.info("[Initialize Redis Configuration]");
	}

	@Bean(name = "jedisPoolConfig")
	public JedisPoolConfig initialRedisPoolConfiguration() {
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		jedisPoolConfig.setMaxTotal(Integer.valueOf(env.getProperty(PropertyNames.MAX_ACTIVE)));
		jedisPoolConfig.setMaxIdle(Integer.valueOf(env.getProperty(PropertyNames.MAX_IDLE)));
		jedisPoolConfig.setTestOnBorrow(Boolean.valueOf(env.getProperty(PropertyNames.TEST_ON_BORROW)));
		log.info("JedisPoolConfig Created");
		return jedisPoolConfig;
	}

	@Bean(name = "connectionFactory")
	public JedisConnectionFactory connectionFactory() {
		JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
		connectionFactory.setPoolConfig(initialRedisPoolConfiguration());
		connectionFactory.setHostName(env.getProperty(PropertyNames.REDIS_HOST));
		connectionFactory.setPort(Integer.valueOf(env.getProperty(PropertyNames.REDIS_PORT)));
		log.info("JedisConnectionFactory Created");
		return connectionFactory;
	}

	@Primary
	@Bean(name = "redisTemplate")
	public StringRedisTemplate redisTemplate() {
		StringRedisTemplate redisTemplate = new StringRedisTemplate();
		redisTemplate.setConnectionFactory(connectionFactory());
		redisTemplate.setEnableTransactionSupport(false);
		log.info("StringRedisTemplate Created");
		return redisTemplate;
	}
}
